/*
 * Copyright (C) 2011 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import java.util.concurrent.ConcurrentHashMap;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.download.DownloadManager;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.AppSecurityPermissions;
import com.mol.market.common.util.DialogUtil;
import com.mol.market.common.util.DialogUtil.WarningDialogListener;
import com.mol.market.common.util.ImageUtils;
import com.mol.market.common.util.StringUtils;
import com.mol.market.common.util.ThemeManager;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.DownloadInfo;
import com.mol.market.common.vo.ProductDetail;
import com.mol.market.common.vo.RecommendTopic;
import com.mol.market.common.vo.TagsInfo;
import com.mol.market.common.widget.BaseActivity;
import com.mol.market.common.widget.CategoryTagView;
import com.mol.market.common.widget.CategoryTagView.TagViewListener;

/**
 * 产品详细信息页<br>
 * 用以展示应用所有的详细信息。<br>
 * 
 * @author andrew
 * @date 2011-3-22
 * 
 */
public class ProductInfoActivity extends BaseActivity implements ApiAsyncTask.ApiRequestListener,
        OnClickListener, Observer,TagViewListener {
    
    private static final int MORE_PRODUCT_ID = 100;
    private static final int MASTER_ID = 200;

    /**
     * 产品信息滑动展示控件
     */
    private ScrollView mScrollView;
    
    /**
     * 产品权限列表
     */
    private LinearLayout mSecurityList;
    
    /**
     * 产品权限声明控件
     */
    private RelativeLayout mSecurityView;
    
    /**
     * 权限列表展开指示器
     */
    private ImageView mPermissionIndicator;
    
    /**
     * 产品短描述信息文本
     */
    private TextView mShortDescription;
    
    /**
     * 产品长描述信息文本
     */
    private TextView mLongDescription;
    
    /**
     * 展示更多产品描述信息按钮
     */
    private Button mMoreButton;

    /**
     * 产品详细
     */
    private ProductDetail mProduct;
    private boolean mIsShortDescription = true;
    private boolean isInit = false;
    private boolean isPermissionShow;

    /**
     * 本应用的初始状态
     */
    private int mInitAppStatus;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mSession.addObserver(this);
        final Intent intent = getIntent();
        mProduct = (ProductDetail) intent.getSerializableExtra(Constants.EXTRA_PRDUCT_DETAIL);
        setContentView(R.layout.activity_product_info_layout);
        
        initViewsByTheme();
        initGallery(mProduct);
        initDescriptionView(mProduct);
        initRatingLayout(mProduct);
        initAppInfo(mProduct);
        initPermissionView(mProduct);
        initActionBar(mProduct);
        switchActionBarStatus(mCurrentStatus);

        MarketAPI.getRecommendByApp(getApplicationContext(), this, mProduct.getPid());
//        MarketAPI.getMasterContains(getApplicationContext(), this, mProduct.getPid());
//        MarketAPI.getCategoryTagsInDetails(getApplicationContext(), this, mProduct.getPid());
    }
    
    /**
     * Action Bar
     */
    private LinearLayout mActionBar;
    
    /*
     * 初始化当前主题下的资源
     */
    private void initViewsByTheme() {
        mActionBar = (LinearLayout) findViewById(R.id.action_bar);
        mActionBar.setBackgroundResource(ThemeManager.getResource(mSession,
                ThemeManager.KEY_ACTION_BAR_BG));
        RelativeLayout rlLeft = (RelativeLayout) mActionBar.findViewById(R.id.action_btn_left);
        rlLeft.setBackgroundResource(ThemeManager.getResource(mSession,
                ThemeManager.KEY_ACTION_BAR_OPERATION_BG));
        rlLeft.setOnClickListener(this);
        RelativeLayout rlRight = (RelativeLayout) mActionBar.findViewById(R.id.action_btn_right);
        rlRight.setBackgroundResource(ThemeManager.getResource(mSession,
                ThemeManager.KEY_ACTION_BAR_OPERATION_BG));
        rlRight.setOnClickListener(this);
        TextView tvLeft = (TextView) mActionBar.findViewById(R.id.tv_left);
        tvLeft.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT));
        TextView tvRight = (TextView) mActionBar.findViewById(R.id.tv_right);
        tvRight.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT));
        ImageView splitter = (ImageView) findViewById(R.id.action_splitter);
        splitter.setBackgroundResource(ThemeManager.getResource(mSession,
                ThemeManager.KEY_ACTION_BAR_SPLITTER));
    }

    @Override
    protected void onResume() {
        super.onResume();
//        TCAgent.onResume(getParent());
        
        // 重新刷新应用的状态
        if (isInit) {
            initActionBar(mProduct);
            switchActionBarStatus(mCurrentStatus);
            initRatingLayout(mProduct);
            reloadImage();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
//        TCAgent.onPause(getParent());
        recycleImage();
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSession.deleteObserver(this);
        mScrollView = null;
        mSecurityList = null;
        mSecurityView = null;
        mPermissionIndicator = null;
        mShortDescription = null;
        mLongDescription = null;
        mMoreButton = null;
        mProduct = null;
    }
    
    /*
     * 计算描述信息是否过长
     */
    private boolean mesureDescription(TextView shortView, TextView longView) {
        final int shortHeight = shortView.getHeight();
        final int longHeight = longView.getHeight();
        if (longHeight > shortHeight) {
            shortView.setVisibility(View.VISIBLE);
            longView.setVisibility(View.GONE);
            return true;
        }
        shortView.setVisibility(View.GONE);
        longView.setVisibility(View.VISIBLE);
        return false;
    }

    /*
     * 切换【更多】按钮状态
     */
    private void toogleMoreButton() {
        if (mIsShortDescription) {
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8,
                    Constants.DETAIL_CLICK_MORE);
            mShortDescription.setVisibility(View.GONE);
            mLongDescription.setVisibility(View.VISIBLE);
            mMoreButton.setText(getString(R.string.label_less));
        } else {
            mShortDescription.setVisibility(View.VISIBLE);
            mLongDescription.setVisibility(View.GONE);
            mMoreButton.setText(getString(R.string.label_more));
        }
        mIsShortDescription = !mIsShortDescription;
    }

    /*
     * 初始化产品描述信息
     */
    private void initDescriptionView(ProductDetail product) {

        mScrollView = (ScrollView) findViewById(R.id.parent_scroll);

        final FrameLayout frame = (FrameLayout) findViewById(R.id.app_description);
        ViewTreeObserver vto = frame.getViewTreeObserver();

        mShortDescription = (TextView) findViewById(R.id.app_description1);
        mShortDescription.setText(product.getLongDescription());
        mShortDescription.setOnClickListener(this);
        mLongDescription = (TextView) findViewById(R.id.app_description2);
        mLongDescription.setText(product.getLongDescription());
        mLongDescription.setOnClickListener(this);

        mMoreButton = (Button) findViewById(R.id.btn_more);
        mMoreButton.setOnClickListener(this);

        vto.addOnPreDrawListener(new OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (isInit)
                    return true;
                if (mesureDescription(mShortDescription, mLongDescription)) {
                    mMoreButton.setVisibility(View.VISIBLE);
                }
                isInit = true;
                return true;
            }
        });
    }

    /*
     * 初始化产品的详细信息（大小，开发者，下载量...）
     */
    private void initAppInfo(ProductDetail product) {

        RatingBar rating = (RatingBar) findViewById(R.id.rb_app_rating);
        rating.setRating(product.getRating());

//        TextView ratingNum = (TextView) findViewById(R.id.tv_app_rating_num);
//        ratingNum.setText(getString(R.string.label_comments, product.getRatingCount()));

        TextView downloadNum = (TextView) findViewById(R.id.app_download);
        downloadNum.setText(getString(R.string.label_downloaded,
                StringUtils.getDownloadInterval(product.getDownloadCount())));

//        TextView appAuthor = (TextView) findViewById(R.id.tv_app_author);
//        appAuthor.setText(getString(R.string.label_author, product.getAuthorName()));

        TextView appSize = (TextView) findViewById(R.id.app_size);
        appSize.setText(getString(R.string.label_size, 
                StringUtils.formatSize(product.getAppSize())));

        TextView appVersion = (TextView) findViewById(R.id.app_version);
        appVersion.setText(getString(R.string.label_version, product.getVersionName()));
    }

    /*
     * 初始化权限列表
     */
    private void initPermissionView(ProductDetail product) {

        String permission = product.getPermission();
        String[] permissionList = null;
        if (!TextUtils.isEmpty(permission)) {
            permissionList = permission.split(",");
        }
        AppSecurityPermissions asp = new AppSecurityPermissions(this, permissionList);
        mSecurityList = (LinearLayout) findViewById(R.id.security_settings_list);
        mSecurityList.addView(asp.getPermissionsView());

        mSecurityView = (RelativeLayout) findViewById(R.id.auth_declare);
        mSecurityView.setOnClickListener(this);
        
        mPermissionIndicator = (ImageView) mSecurityView.findViewById(R.id.auth_more);
    }

    /*
     * 初始化应用截图Gallery
     */
    private void initGallery(ProductDetail product) {
        
        ArrayList<String> mUrls = new ArrayList<String>();
        String[] screenUrl = product.getScreenshotLdpi();
        for (String url : screenUrl) {
            if (TextUtils.isEmpty(url)) {
                continue;
            }
            mUrls.add(url);
        }
        if (mUrls.size() > 0) {

            LayoutInflater inflater = getLayoutInflater();
            LinearLayout background = (LinearLayout) findViewById(R.id.galley_layout);

            final int length = mUrls.size();
            for (int i = 0; i < length; i++) {

                String url = mUrls.get(i);
                ImageView v = (ImageView) inflater
                        .inflate(R.layout.gallery_item, background, false);
                v.setTag(i);
                v.setOnClickListener(mScreenShotClickListener);
                ImageUtils.downloadDeatilScreenshot(getApplicationContext(), url, v);
                background.addView(v);
            }
        }
    }
    
    /*
     * 回收图片资源，避免内存泄露
     */
    private void recycleImage() {

        LinearLayout background = (LinearLayout) findViewById(R.id.galley_layout);
        final int childNum = background.getChildCount();

        for (int i = 0; i < childNum; i++) {
            ImageView v = (ImageView) background.getChildAt(i);
            BitmapDrawable d = (BitmapDrawable) v.getDrawable();
            v.setImageDrawable(null);
            if (d != null) {
                Bitmap b = d.getBitmap();
                if (b != null) {
                    b.recycle();
                }
                d.setCallback(null);
            }
        }
    }
    
    /*
     * 重新加载图片资源
     */
    private void reloadImage() {

        ArrayList<String> mUrls = new ArrayList<String>();
        String[] screenUrl = mProduct.getScreenshotLdpi();
        for (String url : screenUrl) {
            if (TextUtils.isEmpty(url)) {
                continue;
            }
            mUrls.add(url);
        }
        LinearLayout background = (LinearLayout) findViewById(R.id.galley_layout);
        final int childNum = background.getChildCount();

        for (int i = 0; i < childNum; i++) {
            ImageView v = (ImageView) background.getChildAt(i);
            String url = mUrls.get(i);
            ImageUtils.downloadDeatilScreenshot(getApplicationContext(), url, v);
        }
    }

    private OnClickListener mScreenShotClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8,
                    Constants.DETAIL_CLICK_SNAPSHOT);
            Integer pos = (Integer) v.getTag();
            Intent screenShotIntent = new Intent(getApplicationContext(), ScreenshotActivity.class);
            screenShotIntent.putExtra(Constants.EXTRA_PRDUCT_DETAIL, mProduct);
            screenShotIntent.putExtra(Constants.EXTRA_SCREENSHOT_ID, pos);
            startActivity(screenShotIntent);
        }
    };

    /*
     * 切换权限列表的状态
     */
    private void tooglePermissionView() {

        if (isPermissionShow) {
            mSecurityList.setVisibility(View.GONE);
            mPermissionIndicator.setImageResource(R.drawable.more_indicator_details);
            mPermissionIndicator.setBackgroundDrawable(null);
        } else {
            mPermissionIndicator.setImageResource(R.drawable.more_indicator_back);
            mPermissionIndicator.setBackgroundResource(R.drawable.update_all_bg);
            mSecurityList.setVisibility(View.VISIBLE);
            mScrollView.post(new Runnable() {
                @Override
                public void run() {
                    mScrollView.pageScroll(ScrollView.FOCUS_DOWN);
                }
            });
        }
        isPermissionShow = !isPermissionShow;
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
        case R.id.auth_declare:

            tooglePermissionView();
            break;

        case R.id.app_description1:
        case R.id.app_description2:
        case R.id.btn_more:

            toogleMoreButton();
            break;

//        case R.id.info_view:
//
//            // 登录
//            Utils.gotoLogin(this);
//            break;
            
        case MORE_PRODUCT_ID:
            
            // 前往产品页
            String pkgName = (String) v.getTag();
//            Utils.gotoProductDeatil(this, pkgName);
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8,
                    Constants.DETAIL_DISCOVER_APP);
            break;
            
        case MASTER_ID:
            
            // 前往达人专题详细页
            RecommendTopic topic = (RecommendTopic) v.getTag();
            Utils.gotoMaster(this, topic);
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, 
                    String.format(Constants.DETAIL_DISCOVER_MASTER, topic.title));
            break;
            
        case R.id.action_btn_left:
            
            handleLeftAction(mCurrentStatus);
            break;
            
        case R.id.action_btn_right:
            
            handleRightAction(mCurrentStatus);
            break;
            
        case R.id.operation:

            if (mCurrentStatus == STATUS_PENDING) {
                // 开始下载
                DownloadInfo info = mSession.getDownloadingList().get(mProduct.getPackageName());
                if (info != null) {
                    mSession.getDownloadManager().resumeDownload(info.id);
                }
            } else {
                // 取消下载
                mSession.getDownloadManager().cancelDownload(mDownloadInfo.id);
                mSession.removeStarted(mDownloadInfo.mPackageName);
                mProduct.isPendingDownload = false;
                resetActionBar();
            }
            break;

        case R.id.pause:

            mSession.getDownloadManager().pauseDownload(mDownloadInfo.id);
            mSession.removeStarted(mDownloadInfo.mPackageName);
            mProduct.isPendingDownload = true;
            resetActionBar();

        }
    }
    
    /*
     * 重置ActionBar回初始状态
     */
    private void resetActionBar() {
        mCurrentStatus = mInitAppStatus;
        mDownloadStatusBar.setVisibility(View.INVISIBLE);
        mDownloadProgress.setProgress(0);
        mActionBar.setVisibility(View.VISIBLE);
        switchActionBarStatus(mCurrentStatus);
    }
    
    /*
     * 处理ActionBar左边按钮的动作
     */
    private void handleLeftAction(int status) {

        switch (status) {
        
        case STATUS_UNINSTALLED:
        case STATUS_UPDATABLE:

            // 开始下载
            Intent i = new Intent(ProductDetailActivity.ACTION_DOWNLOAD);
            i.putExtra(Constants.EXTRA_PRDUCT_DETAIL, mProduct);
            sendBroadcast(i);
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, 
                    Constants.DETAIL_DOWNLOAD);
            break;
            
        case STATUS_INSTALLED:

            // 打开此应用
            Utils.openApk(getApplicationContext(), mProduct.getPackageName());
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, 
                    Constants.DETAIL_OPEN);
            break;
            
        case STATUS_DOWNLOADED:
        case STATUS_UPDATE_DOWNLOADED:

            // 开始安装
            excuteInstallation();
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, 
                    Constants.DETAIL_INSTALL);
            break;

        case STATUS_PENDING:
            
            // 马上下载
            DownloadInfo info = mSession.getDownloadingList().get(mProduct.getPackageName());
            if (info != null) {
                mSession.getDownloadManager().resumeDownload(info.id);
            }
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, 
                    Constants.DETAIL_QUICK_DOWNLOAD);
            break;
            
        case STATUS_ERROR:

            // 恢复下载
            DownloadInfo appInfo = mSession.getDownloadingList().get(mProduct.getPackageName());
            if (appInfo != null) {
                mSession.getDownloadManager().restartDownload(appInfo.id);
            }
            break;
            
        default:
            break;
        }
    }
    
    /*
     * 安装前检查签名一致性
     */
    private void excuteInstallation() {
        // 下载完成
        if (Utils.compareFileWithPathAndPkg(getApplicationContext(), mProduct.getFilePath(),
                mProduct.getPackageName())) {
            Utils.installApk(getApplicationContext(), new File(mProduct.getFilePath()));
            return;
        }

        DialogUtil.createComfirmDownloadDialog(this, false, new WarningDialogListener() {

            @Override
            public void onWarningDialogOK(int id) {
                mSession.mNotSameApps.put(mProduct.getPackageName(), mProduct.getFilePath());
                Utils.uninstallApk(getApplicationContext(), mProduct.getPackageName());
            }

            @Override
            public void onWarningDialogCancel(int id) {
            }
        }).show();
    }
    
    /*
     * 处理ActionBar左边按钮的动作
     */
    private void handleRightAction(int status){
        
        switch (status) {
        case STATUS_UNINSTALLED:

            // 加入下载队列
            Intent i = new Intent(ProductDetailActivity.ACTION_DOWNLOAD);
            mProduct.isPendingDownload = true;
            i.putExtra(Constants.EXTRA_PRDUCT_DETAIL, mProduct);
            sendBroadcast(i);
            mCurrentStatus = STATUS_PENDING;
            switchActionBarStatus(mCurrentStatus);
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, 
                    Constants.DETAIL_ADD_QUEUE);
            break;
        case STATUS_INSTALLED:
        case STATUS_UPDATABLE:
        case STATUS_UPDATE_DOWNLOADED:

            // 卸载
            Utils.uninstallApk(getApplicationContext(), mProduct.getPackageName());
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, 
                    Constants.DETAIL_UNINSTALL);
            break;
            
        case STATUS_DOWNLOADED:
            
            // 删除
            mSession.getDownloadManager().deleteDownloadedFile(mDownloadInfo.id);
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, 
                    Constants.DETAIL_DEL_FILE);
            break;
            
        case STATUS_ERROR:
        case STATUS_PENDING:
            
            // 移除队列
            DownloadInfo info = mSession.getDownloadingList().get(mProduct.getPackageName());
            if (info != null) {
                info.mStatus = DownloadManager.Impl.STATUS_CANCELED;
                mSession.notifyDataChanged();
                mSession.getDownloadManager().deleteDownloadedFile(info.id);
                mSession.removeStarted(info.mPackageName);
                mProduct.isPendingDownload = false;
            }
            mCurrentStatus = mInitAppStatus;
            switchActionBarStatus(mCurrentStatus);
            Utils.trackEvent(getApplicationContext(), Constants.GROUP_8, 
                    Constants.DETAIL_POP_QUEUE);
            break;
            
        default:
            break;
        }
    }
    
    private long mLastRatingTime = 0;
    // 刷新评分
    private void refreshRatingView(int rating) {
        if (rating > 0) {
            mMyRating.setRating(rating);
        }
        // 可以修改评分状态
        mLastRatingTime = 1;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(int method, Object obj) {

        switch (method) {
        case MarketAPI.ACTION_GET_RECOMMEND_BY_APP:
            // 更多推荐应用
            isMoreAppLoaded = true;
            mMoreApps = (ArrayList<HashMap<String, Object>>) ((HashMap<String, Object>) obj)
                    .get(Constants.KEY_PRODUCT_LIST);
            initMoreView();
            break;

//        case MarketAPI.ACTION_GET_MASTER_CONTAINS:
//            // 收录此应用的达人
//            isMasterLoaded = true;
//            mMasters = (ArrayList<HashMap<String, Object>>) ((HashMap<String, Object>) obj)
//                    .get(Constants.KEY_MASTER_CONTAINS_LIST);
//            initMoreView();
//            break;

        case MarketAPI.ACTION_GET_MYRATING:
            // 获取我的评分
            refreshRatingView(Utils.getInt((String) obj));
            break;
            
        case MarketAPI.ACTION_ADD_RATING:
            // 新增我的评分
            mRanking.setText(R.string.label_ranking_over);
            break;
            
        case MarketAPI.ACTION_GET_TAGS_IN_DETAILS:
            // 标签
            showTagsViewIfNeed(obj);
            break;
            
        default:
            break;
        }
    }
    
    /**
     * 根据数据，决定是否显示标签页。
     * @param obj
     */
    private void showTagsViewIfNeed(Object obj){
        View tagView = findViewById(R.id.rl_tagsview);
        if (obj instanceof List) {
            List<TagsInfo> tagsList = (List<TagsInfo>) obj;
            if(tagsList.size() != 0){
                CategoryTagView tag = (CategoryTagView) findViewById(R.id.tv_tagview);
                tag.setTags((List<TagsInfo>) obj);
                tag.setTagsViewOnClickListener(this);
                tagView.setVisibility(View.VISIBLE);
                return ;
            }
        }
        tagView.setVisibility(View.GONE);
    }

    @Override
    public void onError(int method, int statusCode) {
        switch (method) {
        case MarketAPI.ACTION_GET_RECOMMEND_BY_APP:
            // 更多推荐应用
            isMoreAppLoaded = true;
            break;

//        case MarketAPI.ACTION_GET_MASTER_CONTAINS:
//            // 收录此应用的达人
//            isMasterLoaded = true;
//            break;
        default:
            break;
        }
    }

    private boolean isMoreAppLoaded = false;
    private ArrayList<HashMap<String, Object>> mMoreApps;
//    private boolean isMasterLoaded = false;
    private ArrayList<HashMap<String, Object>> mMasters;

    /*
     * 初始化更多推荐应用
     * 
     * 1 判断达人列表是否加载成功，如果成功一并显示 <br>
     * 2 如果加载失败就隐藏此栏 <br>
     */
    private void initMoreView() {

        if (isMoreAppLoaded) {

            initMoreAppView();
//            initMasterView();
        }
    }

    /*
     * 如果用户安装应用后，可以进行评级
     */
    private void initRatingLayout(ProductDetail product) {
        
        HashSet<String> installed = mSession.getInstalledApps();
        if (!installed.contains(product.getPackageName())) {
            // 用户没有安装此应用
            View v = findViewById(R.id.rating_layout);
            if (v != null) {
                v.setVisibility(View.GONE);
            }
            return;
        }
        
//        // 导入评级部分布局
//        View info = findViewById(R.id.info_view);
//        View rating = findViewById(R.id.rating_view);
//        View root = null;
//        if (info == null) {
//            root = ((ViewStub) findViewById(R.id.stub_import_rating)).inflate();
//            info = root.findViewById(R.id.info_view);
//            info.setOnClickListener(this);
//            rating = root.findViewById(R.id.rating_view);
//            initRatingView(rating);
//        }
//
//        if (mSession.isLogin()) {
//            // 已经登录，可以评级
//            info.setVisibility(View.GONE);
//            rating.setVisibility(View.VISIBLE);
//            MarketAPI.getMyRating(getApplicationContext(), this, mProduct.getPid());
//
//        } else {
//            // 没有登录，不能评级
//            info.setVisibility(View.VISIBLE);
//            rating.setVisibility(View.GONE);
//        }
    }
    
    private RatingBar mMyRating;
    private TextView mRanking;
    private Handler mHandler = new Handler();
    
    /*
     * 初始化评级控件
     */
    private void initRatingView(View root) {
        mMyRating = (RatingBar) root.findViewById(R.id.rb_myrating);
        mRanking = (TextView) root.findViewById(R.id.tv_ranking);
        mMyRating.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, final float rating, boolean fromUser) {

                int ranking = (int) rating;
                switch (ranking) {
                case 1:
                    mRanking.setText(R.string.label_ranking_1);
                    break;
                case 2:
                    mRanking.setText(R.string.label_ranking_2);
                    break;
                case 3:
                    mRanking.setText(R.string.label_ranking_3);
                    break;
                case 4:
                    mRanking.setText(R.string.label_ranking_4);
                    break;
                case 5:
                    mRanking.setText(R.string.label_ranking_5);
                    break;

                default:
                    break;
                }

                long currentTime = System.currentTimeMillis();
                if ((mLastRatingTime != 0) && (currentTime - mLastRatingTime > 2000)) {
                    // 防止用户过于频繁提交数据
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {

                            // Bug fixed 2011/9/17
                            if (mProduct == null) {
                                return;
                            }
                            MarketAPI.addRating(getApplicationContext(), ProductInfoActivity.this,
                                    mProduct.getPid(), (int) rating);
                        }
                    }, 2000);

                    mLastRatingTime = currentTime;
                }
            }
        });
    }
    
    /*
     * 初始化更多应用
     */
    private void initMoreAppView() {

        if (mMoreApps == null || mMoreApps.size() == 0) {
            return;
        }

        // 导入更多应用部分布局
        View root = ((ViewStub) findViewById(R.id.stub_import_enjoy)).inflate();

        // 横向滑动布局
        LinearLayout parent = (LinearLayout) root.findViewById(R.id.more_layout);

        for (HashMap<String, Object> item : mMoreApps) {

            RelativeLayout v = (RelativeLayout) getLayoutInflater().inflate(
                    R.layout.product_maybe_enjoy, parent, false);
            ImageView icon = (ImageView) v.findViewById(R.id.more_app_logo);
            TextView name = (TextView) v.findViewById(R.id.more_app_name);

            String userIconUrl = (String) item.get(Constants.KEY_ICON_URL);
            ImageUtils.download(getApplicationContext(), userIconUrl, icon,
                    R.drawable.loading_icon, true, false);
            name.setText((String) item.get(Constants.KEY_PRODUCT_NAME));
            
            v.setId(100);
            v.setTag((String) item.get(Constants.KEY_PRODUCT_PACKAGE_NAME));
            v.setOnClickListener(this);
            parent.addView(v);
        }
    }

    /*
     * 初始化更多达人
     */
    private void initMasterView() {

        if (mMasters == null || mMasters.size() == 0) {
            return;
        }

        // 导入达人部分布局
        View root = ((ViewStub) findViewById(R.id.stub_import_expert)).inflate();

        // 横向滑动布局
        LinearLayout parent = (LinearLayout) root.findViewById(R.id.expert_layout);

        for (HashMap<String, Object> item : mMasters) {

            RecommendTopic topic = Utils.mapToTopic(item);
            RelativeLayout v = (RelativeLayout) getLayoutInflater().inflate(
                    R.layout.product_find_expert, parent, false);
            ImageView icon = (ImageView) v.findViewById(R.id.iv_user_icon);

            ImageUtils.download(getApplicationContext(), topic.icon, icon,
                    R.drawable.default_user_big, true, false);
            
            TextView name = (TextView) v.findViewById(R.id.tv_recommendation_name);
            name.setText(topic.user);
            
            v.setId(MASTER_ID);
            v.setTag(topic);
            v.setOnClickListener(this);
            parent.addView(v);
        }
    }
    
    private static final int STATUS_UNINSTALLED = 0;
    private static final int STATUS_INSTALLED = 1;
    private static final int STATUS_UPDATABLE = 2;
    private static final int STATUS_DOWNLOADED = 3;
    private static final int STATUS_UPDATE_DOWNLOADED = 4;
    private static final int STATUS_DOWNLOADING = 5;
    private static final int STATUS_PENDING = 6;
    private static final int STATUS_ERROR = 7;
    private int mCurrentStatus;
    
    /*
     * 切换ActionBar的状态
     */
    private void switchActionBarStatus(int status) {

        switch (status) {
        case STATUS_UNINSTALLED:
        {
            ImageView iconL = (ImageView) findViewById(R.id.iv_left);
            iconL.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_DOWNLOAD));
            
            TextView textL = (TextView) findViewById(R.id.tv_left);
            int payCategory = mProduct.getPayCategory();
            if (Constants.PAY_TYPE_FREE == payCategory) {
                textL.setText(R.string.label_download);
            } else if (Constants.PAY_TYPE_PAID == payCategory) {
                textL.setText(getString(R.string.label_paid, mProduct.getPrice()));
            }
            ImageView iconR = (ImageView) findViewById(R.id.iv_right);
            iconR.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_PENDING));
            TextView textR = (TextView) findViewById(R.id.tv_right);
            textR.setText(R.string.label_pending_download);
            break;
        }
        case STATUS_INSTALLED:
        {
            ImageView iconL = (ImageView) findViewById(R.id.iv_left);
            iconL.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_OPEN));
            TextView textL = (TextView) findViewById(R.id.tv_left);
            textL.setText(R.string.label_open);
            ImageView iconR = (ImageView) findViewById(R.id.iv_right);
            iconR.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_UNINSTALL));
            TextView textR = (TextView) findViewById(R.id.tv_right);
            textR.setText(R.string.label_uninstall);
            break;
        }
        case STATUS_UPDATABLE:
        {
            ImageView iconL = (ImageView) findViewById(R.id.iv_left);
            iconL.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_DOWNLOAD));
            TextView textL = (TextView) findViewById(R.id.tv_left);
            textL.setText(R.string.label_update);
            ImageView iconR = (ImageView) findViewById(R.id.iv_right);
            iconR.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_UNINSTALL));
            TextView textR = (TextView) findViewById(R.id.tv_right);
            textR.setText(R.string.label_uninstall);
            break;
        }
        case STATUS_DOWNLOADED:
        {
            ImageView iconL = (ImageView) findViewById(R.id.iv_left);
            iconL.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_INSTALL));
            TextView textL = (TextView) findViewById(R.id.tv_left);
            textL.setText(R.string.label_install);
            ImageView iconR = (ImageView) findViewById(R.id.iv_right);
            iconR.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_UNINSTALL));
            TextView textR = (TextView) findViewById(R.id.tv_right);
            textR.setText(R.string.label_delete);
            break;
        }
        case STATUS_UPDATE_DOWNLOADED:
        {
            ImageView iconL = (ImageView) findViewById(R.id.iv_left);
            iconL.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_INSTALL));
            TextView textL = (TextView) findViewById(R.id.tv_left);
            textL.setText(R.string.label_install);
            ImageView iconR = (ImageView) findViewById(R.id.iv_right);
            iconR.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_UNINSTALL));
            TextView textR = (TextView) findViewById(R.id.tv_right);
            textR.setText(R.string.label_uninstall);
            break;
        }
        case STATUS_ERROR:
        {
            ImageView iconL = (ImageView) findViewById(R.id.iv_left);
            iconL.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_START));
            TextView textL = (TextView) findViewById(R.id.tv_left);
            textL.setText(R.string.label_resume);
            ImageView iconR = (ImageView) findViewById(R.id.iv_right);
            iconR.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_CANCEL));
            TextView textR = (TextView) findViewById(R.id.tv_right);
            textR.setText(R.string.label_cancel);
            break;
        }
        case STATUS_PENDING:
        {
            ImageView iconL = (ImageView) findViewById(R.id.iv_left);
            iconL.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_START));
            TextView textL = (TextView) findViewById(R.id.tv_left);
            textL.setText(R.string.label_start);
            ImageView iconR = (ImageView) findViewById(R.id.iv_right);
            iconR.setImageResource(
                    ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_CANCEL));
            TextView textR = (TextView) findViewById(R.id.tv_right);
            textR.setText(R.string.label_cancel);
            break;
        }
        default:
            break;
        }
    }
    
    /*
     * 刷新应用的下载进度
     */
    private void refreshDownloadingStatus(DownloadInfo info) {
        
        synchronized (this) {
            mDownloadInfo = info;
        }
        if (info == null) {
            return;
        }
        
        // 如果第一次刷新需要先初始化下载进度栏
        initDownloadStatusBar();
        
        final int currentStatus = info.mStatus;
        
        if (DownloadManager.Impl.isStatusNotCancelError(currentStatus)) {
            // 下载失败
            mCurrentStatus = STATUS_ERROR;
            mActionBar.setVisibility(View.VISIBLE);
            mDownloadStatusBar.setVisibility(View.INVISIBLE);

        } else if (DownloadManager.Impl.isStatusWaiting(info.mControl)) {
            // 下载队列中
            mCurrentStatus = STATUS_PENDING;
            mActionBar.setVisibility(View.VISIBLE);
            mDownloadStatusBar.setVisibility(View.INVISIBLE);

        } else if (DownloadManager.Impl.isStatusPending(currentStatus)) {
            // 网络连接中
            mCurrentStatus = STATUS_DOWNLOADING;
            mDownloadStatusTitle.setText(R.string.download_try);
            mDownloadProgress.setIndeterminate(true);
            
        } else if (DownloadManager.Impl.isStatusRunning(currentStatus)) {
            // 下载中状态
            mDownloadStatusTitle.setText(R.string.download_status_downloading);
            mDownloadProgress.setIndeterminate(false);
            mDownloadProgress.setProgress(info.mProgressNumber);
            mDownloadRemainSize.setText(Utils.calculateRemainBytes(getApplicationContext(),
                    info.mCurrentSize, info.mTotalSize));
            mBtnCancelDownload.setText(R.string.cancel_downloads);
            mCurrentStatus = STATUS_DOWNLOADING;
            
        } else if (DownloadManager.Impl.isStatusSuccess(currentStatus)) {
            // 下载成功
            if (mInitAppStatus == STATUS_UPDATABLE) {
                mCurrentStatus = STATUS_UPDATE_DOWNLOADED;
            } else {
                mCurrentStatus = STATUS_DOWNLOADED;
            }
            mProduct.setFilePath(info.mFilePath);
            mDownloadStatusBar.setVisibility(View.INVISIBLE);
            mDownloadProgress.setProgress(0);
            mActionBar.setVisibility(View.VISIBLE);
            
        } else if (DownloadManager.Impl.isStatusInformational(currentStatus)) {
            // 下载等待中
            mCurrentStatus = mInitAppStatus;
            mDownloadStatusBar.setVisibility(View.VISIBLE);
            mActionBar.setVisibility(View.INVISIBLE);
            
        } else if (currentStatus == DownloadManager.Impl.STATUS_INSTALLED) {
            
            mCurrentStatus = STATUS_INSTALLED;
            mDownloadStatusBar.setVisibility(View.INVISIBLE);
            mActionBar.setVisibility(View.VISIBLE);
            
        } else {
            // 下载失败
            mCurrentStatus = mInitAppStatus;
            mDownloadStatusBar.setVisibility(View.INVISIBLE);
            mDownloadProgress.setProgress(0);
            mActionBar.setVisibility(View.VISIBLE);
        }
        switchActionBarStatus(mCurrentStatus);
    }
    
    /**
     * 下载进度显示栏
     */
    private RelativeLayout mDownloadStatusBar;
    
    /**
     * 下载取消控制按钮
     */
    private TextView mBtnCancelDownload;

    /**
     * 暂停下载按钮
     */
    private TextView mBtnPauseDownload;
    
    /**
     * 下载状态标题
     */
    private TextView mDownloadStatusTitle;
    
    /**
     * 应用下载剩余大小
     */
    private TextView mDownloadRemainSize;
    
    /**
     * 下载进度
     */
    private ProgressBar mDownloadProgress;
    
    /*
     * 初始化下载状态栏
     */
    private void initDownloadStatusBar() {
        
        if (mDownloadStatusBar != null) {
            if (!mDownloadStatusBar.isShown()) {
                mDownloadStatusBar.setVisibility(View.VISIBLE);
            }
            return;
        }
        mActionBar.setVisibility(View.INVISIBLE);
        mDownloadStatusBar = (RelativeLayout) findViewById(R.id.download_status_bar);
        mDownloadStatusBar.setBackgroundResource(ThemeManager.getResource(mSession, 
                ThemeManager.KEY_ACTION_BAR_BG));
        mDownloadStatusBar.setVisibility(View.VISIBLE);

        mBtnPauseDownload = (TextView) mDownloadStatusBar.findViewById(R.id.pause);
        mBtnPauseDownload.setBackgroundResource(ThemeManager.getResource(mSession,
          ThemeManager.KEY_ACTION_BAR_BTN_BG));
        mBtnPauseDownload.setTextAppearance(getApplicationContext(),
          ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT_M));
        mBtnPauseDownload.setOnClickListener(this);
        
        mBtnCancelDownload = (TextView) mDownloadStatusBar.findViewById(R.id.operation);
        mBtnCancelDownload.setBackgroundResource(ThemeManager.getResource(mSession, 
                ThemeManager.KEY_ACTION_BAR_BTN_BG));
        mBtnCancelDownload.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT_M));
        mBtnCancelDownload.setOnClickListener(this);

        mDownloadStatusTitle = (TextView) mDownloadStatusBar.findViewById(R.id.tv_title);
        mDownloadStatusTitle.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT_S));
        mDownloadRemainSize = (TextView) mDownloadStatusBar.findViewById(R.id.tv_status);
        mDownloadRemainSize.setTextAppearance(getApplicationContext(),
                ThemeManager.getResource(mSession, ThemeManager.KEY_ACTION_BAR_FONT_S));
        mDownloadProgress = (ProgressBar) mDownloadStatusBar.findViewById(R.id.progressbar);
        mDownloadProgress.setProgressDrawable(getResources().getDrawable(
                ThemeManager.getResource(mSession, ThemeManager.KEY_PROGRESSBAR)));
    }
    
    /*
     * 初始化ActionBar状态
     */
    private void initActionBar(ProductDetail product) {

        if (mSession.getUpdateList().containsKey(mProduct.getPackageName())) {
            mInitAppStatus = STATUS_UPDATABLE;
        } else if (mSession.getInstalledApps().contains(mProduct.getPackageName())) {
            mInitAppStatus = STATUS_INSTALLED;
        } else {
            mInitAppStatus = STATUS_UNINSTALLED;
        }

        ConcurrentHashMap<String, DownloadInfo> list = mSession.getDownloadingList();

        if (list != null) {

            DownloadInfo info = list.get(product.getPackageName());
            if (info == null) {
                mCurrentStatus = mInitAppStatus;
                return;
            }
            
            mDownloadInfo = info;
            if (DownloadManager.Impl.isStatusWaiting(info.mControl)) {
                
                // 下载队列中
                mCurrentStatus = STATUS_PENDING;
                mActionBar.setVisibility(View.VISIBLE);
                switchActionBarStatus(mCurrentStatus);
                return;
                
            } if (DownloadManager.Impl.isStatusPending(info.mStatus)) {
                
                // 网络连接中
                mActionBar.setVisibility(View.INVISIBLE);
                initDownloadStatusBar();
                mDownloadProgress.setIndeterminate(true);
                mDownloadStatusTitle.setText(R.string.download_try);
                mCurrentStatus = STATUS_DOWNLOADING;
                return;
                
            } else if (DownloadManager.Impl.isStatusRunning(info.mStatus)) {

                // 下载中
                mActionBar.setVisibility(View.INVISIBLE);
                initDownloadStatusBar();
                mCurrentStatus = STATUS_DOWNLOADING;
                return;

            } else if (DownloadManager.Impl.isStatusError(info.mStatus)) {
                
                // 下载中断
                mCurrentStatus = STATUS_ERROR;
                mActionBar.setVisibility(View.VISIBLE);
                switchActionBarStatus(mCurrentStatus);
                return;
                
            } else if (DownloadManager.Impl.isStatusSuccess(info.mStatus)) {
                // 下载完成
                if (Utils.isFileExist(info.mFilePath)) {
                    // 已经下载完成
                    mProduct.setFilePath(info.mFilePath);

                    if (mInitAppStatus == STATUS_UPDATABLE) {
                        mCurrentStatus = STATUS_UPDATE_DOWNLOADED;
                    } else {
                        mCurrentStatus = STATUS_DOWNLOADED;
                    }
                    return;
                }
            }
        }
        mCurrentStatus = mInitAppStatus;
    }
    
    /**
     * 下载管理器管理的状态
     */
    private DownloadInfo mDownloadInfo;

    /*
     * 初始化本应用的状态，已经安装与否
     * 
     * 之后根据用户行为刷新状态
     * 
     * 根据是否安装判断之后的应用状态
     * 
     */
    @SuppressWarnings("unchecked")
    @Override
    public void update(Observable arg0, Object param) {
        if (param instanceof ConcurrentHashMap) {
            ConcurrentHashMap<String, DownloadInfo> mDownloadingTask = 
                (ConcurrentHashMap<String, DownloadInfo>) param;
            DownloadInfo info = mDownloadingTask.get(mProduct.getPackageName());

            if (info == null) {
                return;
            }
            
            refreshDownloadingStatus(info);
        }
    }

    @Override
    public void onTagsViewClick(View v, TagsInfo tag) {
        if(tag == null){
            //unlucky
            return ;
        }
     
        Utils.trackEvent(getApplicationContext(), Constants.GROUP_8,
                String.format(Constants.CLICK_TAG, tag.getTagName()));
        Utils.jumpToPage(this, 
                TagsListActivity.class, 
                false, 
                new String[] {
                    TagsListActivity.TAGS_ID, 
                    TagsListActivity.TAGS_NAME },
                new Serializable[] { 
                    tag.getTagId(), 
                    tag.getTagName() });
    }
}